package com.isoftstone.studentregistration.controller;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import com.isoftstone.studentregistration.util.Result;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;

/**
 * @author Administrator
 * @version v1.0
 * @date 2025/9/7 16:38
 */
@RestController
@RequestMapping("/api")
public class FileController {
    @Value("${file.upload.path}")
    private String fileUploadPath;
    @Value("${file.upload.fileMapper}")
    private String fileMapper;
    @PostMapping("/upload")
    public Result<?> uploadFile(MultipartFile file) throws IOException {
        String fileName = file.getOriginalFilename();
        String fileType = FileUtil.extName(fileName);
        long fileSize = file.getSize();
//        判断uploadFile是否存在，不存在则创建
        File uploadFile = new File(fileUploadPath + fileName);
        if(!uploadFile.getParentFile().exists()){
            uploadFile.getParentFile().mkdirs();
        }
//       重命名文件
        String uuid= IdUtil.fastSimpleUUID();
//        创文件
        String newFileName=uuid+ StrUtil.DOT+fileType;
//        文件地址
        String url=fileMapper+newFileName;
        File newFile=new File(fileUploadPath+newFileName);
//        文件保存到指定目录
        file.transferTo(newFile);
        return Result.success(url);
    }
}
